import Vue from 'vue'
import VueRouter from 'vue-router'
//引入组件实例
import Home from '../views/Home.vue'
// import Product from '../views/Product.vue'
import NotFound  from '../views/404Page.vue';


Vue.use(VueRouter)
// 路由配置数组，router-view会根据获取的地址栏路由信息，
// 结合该数组里的配置信息，决定应该展示哪个组件
// 每个配置信息就是一个对象
const routes = [
  { path: '/', redirect: '/home' }, //路由重定向
  { path: '/home', component: Home },
  //路由懒加载，components要写成一个函数，return引入的组件实例
  { path: '/product', component: ()=> import("../views/Product.vue")},
  { path: '/cart', component: ()=>import('../views/Cart'),
    //路由独享的守卫 在路由配置上直接定义 beforeEnter 守卫
    beforeEnter:((to, from, next) => {
      if(Math.random()>0.5) {
        next();
      }else {
        let res = confirm("当前未登录，是否前去登录")
        if(res){
          next('/mine')
        }
      }
    })
  },
  { path: '/sale/:id/:type', component: ()=>import('../views/Sale.vue'),name:'s'},
  { path: '/mine', component: ()=>import('../views/Mine.vue'),
    // 配置二级路由，需要children字段
    children:[
      { path: '', redirect:to=>{
        return {path:'info',query:{id:333,name:'ljh',price:223}}        
      } },
      // 二级路由的path只写二级路由的路由名，需要把/去掉 
      { path: 'info', component:()=>import('../views/Info.vue') },
      { path: 'order/:id/:name/:price', component:()=>import('../views/Order.vue'),name:"od" },
    ]
  },
  { path: '/hotnews', component: ()=>import('../views/HotNews'),
    children:[
      { path: 'news', component: ()=>import('../components/News') },
      { path: 'images',
        //辅助路由
        components:{
          //default字段默认对应没有name值的router-view
          default:()=>import('../components/Images'),
          //其余字段，与需要展示的插座的name值保持一致
          a:()=>import('../components/Common')
        }
      }
    ]
  },
  { path: '*', component: NotFound } //通配符路由
];

const router = new VueRouter({
  routes
})

// if(savedPosition){
//   return savedPosition
// }else{
//   return {x:0 ,y:0}
// }
//注册一个全局的前置守卫（钩子），会捕捉所有的路由切换，并在切换之前触发
/* router.beforeEach((to,from,next)=>{
  // console.log(to.path,from.path);
  // next();
  if(to.path=='/cart'){
    let mn=Math.random();
    console.log(mn);
    if(mn>0.5){
      alert("未登录");
    }else{
      next();
    }
  }else if(from.name=='s'){
    let mn=Math.random();
    console.log(mn);
    if(mn>0.5){
      alert("未登录");
    }else{
      next();
    }
  }else if(from.path=='/mine/info'){
    let mn=Math.random();
    console.log(mn);
    if(mn>0.5){
      confirm("是否保存数据");
    }else{
      next();
    }
  }else{
    next();
  }
}) */

// 注册一个组件的后置守卫（钩子），也会捕捉所有的路由切换，并在路由切换成功后触发
/* router.afterEach((to,from)=>{
  console.log(`你已经从${to.path}跳转到${from.path} `)
})  */

export default router
